package template;

import com.intellij.openapi.actionSystem.AnActionEvent;
import com.intellij.openapi.actionSystem.CommonDataKeys;

import java.util.Objects;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class CommonUtils {

    /**
     * 刷新项目
     */
    public static void refreshProject(AnActionEvent e){
        Objects.requireNonNull(CommonDataKeys.VIRTUAL_FILE.getData(e.getDataContext())).refresh(false, true);
    }

    /**
     * import包名(取路径“java\"后的)
     *
     * @param absolutePath 绝对路径类似：D:\demo\dem3\app\src\main\java\com\smyk\demo3
     * @return ""
     */
    public static String getImportPackage(String absolutePath) {
        return absolutePath.substring(absolutePath.indexOf("java") + 5).replace("/", ".");
    }


    public static String getBasePackage(String packageName) {
        try {
            String[] strings = packageName.split("\\.");
            StringBuilder stringBuilder = new StringBuilder();
            for (int i = 0; i < strings.length; i++) {
                if (i < 3)
                    stringBuilder.append(strings[i]).append(".");
            }
            //去除最后一个点
            return stringBuilder.substring(0, stringBuilder.length() - 1);
        } catch (Exception e) {
            e.printStackTrace();
            return "";
        }
    }

    /**
     * java 大写转小写加横杠
     */
    public static String camelToUnderline(String param) {
        Pattern p = Pattern.compile("[A-Z]");
        if (param == null || param.equals("")) {
            return "";
        }
        StringBuilder builder = new StringBuilder(param);
        Matcher mc = p.matcher(param);
        int i = 0;
        while (mc.find()) {
            builder.replace(mc.start() + i, mc.end() + i, "_" + mc.group().toLowerCase());
            i++;
        }

        if ('_' == builder.charAt(0)) {
            builder.deleteCharAt(0);
        }
        return builder.toString();
    }
}
